const formatTime = date => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function ab2hex(buffer) {
	var hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function (bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	return hexArr.join('');
}

function phoneFun(phones) {
	var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
	if (!myreg.test(phones)) {
		console.log('手机号格式不正确')
		return false;
	} else {
		console.log('手机号格式正确')
		return true;
	}
}

function isDateYYYYDDMM(sDate) {

	if (!/^[0-9]{8}$/.test(sDate)) {

		return false;

	}

	var year, month, day;

	year = sDate.substring(0, 4);

	month = sDate.substring(4, 6);

	day = sDate.substring(6, 8);

	var iaMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

	if (year < 1700 || year > 2500) return false

	if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) iaMonthDays[1] = 29;

	if (month < 1 || month > 12) return false

	if (day < 1 || day > iaMonthDays[month - 1]) return false

	return true

}

function addresFun(newName) {
	if (newName == '') {
		return false;
	}
	var regEn = /^[\u4e00-\u9fa5\w\.\+()（）\-\·]*$/;

	if (!regEn.test(newName)) {
		console.log("名称不能包含特殊字符.");
		return false;
	} else {
		return true;
	}
}

function str2buffer(str) {
	let val = ""
	if (!str) return;
	let length = str.length;
	let index = 0;
	let array = []
	while (index < length) {
		array.push(str.substring(index, index + 2));
		index = index + 2;
	}
	val = array.join(",");
	// 将16进制转化为ArrayBuffer
	return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
		return parseInt(h, 16)
	})).buffer
}

function inArray(arr, key, val) {
	for (let i = 0; i < arr.length; i++) {
		if (arr[i][key] === val) {
			return i;
		}
	}
	return -1;
}

const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : '0' + n
}

// 判断末尾字符串
function endsWith(str, target) {
	return str.endsWith(target)
}

// 截取末尾字符串
function slice(str, target) {
	var start = str.length - target.length;
	str = str.slice(0, start);
	return str;
}

function formatDate(date) {
	return date.replace(/(\d{4})(\d{2})(\d{2})/g, '$1-$2-$3');
}
//营业执照号码规则
function checkLicense(value) {
	if (value.length == 15) {
		return businessLicense15(value);
	} else {
		var reg = /^([159Y]{1})([1239]{1})([0-9ABCDEFGHJKLMNPQRTUWXY]{6})([0-9ABCDEFGHJKLMNPQRTUWXY]{9})([0-9ABCDEFGHJKLMNPQRTUWXY])$/;
		if (!reg.test(value)) {
			return false;
		} else {
			return true;
		}
		// var str = '0123456789ABCDEFGHJKLMNPQRTUWXY';
		// var ws = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28];
		// var codes = new Array();
		// codes[0] = value.substr(0, value.length - 1);
		// codes[1] = value.substr(value.length - 1, value.length);
		// var sum = 0;
		// for (var i = 0; i < 17; i++) {
		// 	sum += str.indexOf(codes[0].charAt(i)) * ws[i];
		// }
		// var c18 = 31 - (sum % 31);
		// if (c18 == 31) {
		// 	c18 = 'Y';
		// } else if (c18 == 30) {
		// 	c18 = '0';
		// }
		// if (str.charAt(c18) != codes[1].charAt(0)) {
		// 	return false;
		// }
		// return true;
	}
}
function businessLicense15(ints) {
	let ti = 0;
	let si = 0;// pi|11+ti
	let cj = 0;// （si||10==0？10：si||10）*2
	let pj = 10;// pj=cj|11==0?10:cj|11
	let lastNum = '';
	for (let i = 0; i < ints.length; i++) {
		ti = parseInt(ints[i]);
		si = pj + ti;
		cj = (0 == si % 10 ? 10 : si % 10) * 2;
		pj = cj % 11;
		if (i == ints.length - 1) {
			//lastNum =(1 - pj < 0 ? 11 - pj : 1 - pj) % 10;
			lastNum = si % 10
		}
	}
	if (lastNum == 1) {
		return true;
	} else {
		return false
	}
}
function checkIdCard(card) {
	// 规则： 新版8位或18位数字， 旧版10位数字 + 英文字母

	// 样本： 12345678 或 1234567890B

	var reg = /^\d{8}|^[a-zA-Z0-9]{10}|^\d{18}$/

	if (reg.test(card) === false) {

		return {

			respCode: 1,
			respDesc: '台湾居民来往大陆通行证号码不合规'

		}

	} else {
		return {
			respCode: 0,
			respDesc: '校验通过'
		}

	}
}
//港澳居民通行证
function checkHKMacao(code) {
	var tip = "OK";
	var pass = true;
	if (!code || !/^[HMhm]{1}([0-9]{10}|[0-9]{8})$/.test(code)) {
		tip = "港澳居民通行证号码格式错误";
		pass = false;
	}
	return {
		'errCode': pass,
		'errMsg': tip
	};
}

//身份证验证
function IdentityCodeValid(code) {
	var city = {
		11: "北京",
		12: "天津",
		13: "河北",
		14: "山西",
		15: "内蒙古",
		21: "辽宁",
		22: "吉林",
		23: "黑龙江 ",
		31: "上海",
		32: "江苏",
		33: "浙江",
		34: "安徽",
		35: "福建",
		36: "江西",
		37: "山东",
		41: "河南",
		42: "湖北 ",
		43: "湖南",
		44: "广东",
		45: "广西",
		46: "海南",
		50: "重庆",
		51: "四川",
		52: "贵州",
		53: "云南",
		54: "西藏 ",
		61: "陕西",
		62: "甘肃",
		63: "青海",
		64: "宁夏",
		65: "新疆",
		71: "台湾",
		81: "香港",
		82: "澳门",
		91: "国外 "
	};
	var tip = "";
	var pass = true;

	if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
		tip = "身份证号格式错误";
		pass = false;
	} else if (!city[code.substr(0, 2)]) {
		tip = "地址编码错误";
		pass = false;
	} else {
		//18位身份证需要验证最后一位校验位
		if (code.length == 18) {
			code = code.split('');
			//∑(ai×Wi)(mod 11)
			//加权因子
			var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
			//校验位
			var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
			var sum = 0;
			var ai = 0;
			var wi = 0;
			for (var i = 0; i < 17; i++) {
				ai = code[i];
				wi = factor[i];
				sum += ai * wi;
			}
			var last = parity[sum % 11];
			if (parity[sum % 11] != code[17]) {
				tip = "校验位错误";
				pass = false;
			}
		}
	}
	return pass;
}
//中文验证
function isChineseName(name) {
	//把名字中的分隔符（·）去掉，再判断是否全为中文，且长度在范围为2-15
	var nameWithoutDot = name.replace(/\u00b7/g, '');
	console.log(name)
	if (/^[\u4e00-\u9fa5]{2,15}$/i.test(nameWithoutDot)) {
		return true;
	}
	else {
		return false;
	}
}
function luhnCheck(bankno) {
	var lastNum = bankno.substr(bankno.length - 1, 1); //取出最后一位（与luhn进行比较）
	var first15Num = bankno.substr(0, bankno.length - 1); //前15或18位
	var newArr = new Array();
	for (var i = first15Num.length - 1; i > -1; i--) { //前15或18位倒序存进数组
		newArr.push(first15Num.substr(i, 1));
	}
	var arrJiShu = new Array(); //奇数位*2的积 <9
	var arrJiShu2 = new Array(); //奇数位*2的积 >9
	var arrOuShu = new Array(); //偶数位数组
	for (var j = 0; j < newArr.length; j++) {
		if ((j + 1) % 2 == 1) { //奇数位
			if (parseInt(newArr[j]) * 2 < 9) arrJiShu.push(parseInt(newArr[j]) * 2);
			else arrJiShu2.push(parseInt(newArr[j]) * 2);
		} else //偶数位
			arrOuShu.push(newArr[j]);
	}

	var jishu_child1 = new Array(); //奇数位*2 >9 的分割之后的数组个位数
	var jishu_child2 = new Array(); //奇数位*2 >9 的分割之后的数组十位数
	for (var h = 0; h < arrJiShu2.length; h++) {
		jishu_child1.push(parseInt(arrJiShu2[h]) % 10);
		jishu_child2.push(parseInt(arrJiShu2[h]) / 10);
	}

	var sumJiShu = 0; //奇数位*2 < 9 的数组之和
	var sumOuShu = 0; //偶数位数组之和
	var sumJiShuChild1 = 0; //奇数位*2 >9 的分割之后的数组个位数之和
	var sumJiShuChild2 = 0; //奇数位*2 >9 的分割之后的数组十位数之和
	var sumTotal = 0;
	for (var m = 0; m < arrJiShu.length; m++) {
		sumJiShu = sumJiShu + parseInt(arrJiShu[m]);
	}

	for (var n = 0; n < arrOuShu.length; n++) {
		sumOuShu = sumOuShu + parseInt(arrOuShu[n]);
	}

	for (var p = 0; p < jishu_child1.length; p++) {
		sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p]);
		sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p]);
	}
	//计算总和
	sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu) + parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2);

	//计算luhn值
	var k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10;
	var luhn = 10 - k;

	if (lastNum == luhn) {
		return true;
	} else {
		return false;
	}
}
function stringHex2int(r) {
	for (var t, n = r.length, e = new Array(n), i = 0; i < n; i++) 48 <= (t = r.charCodeAt(i)) && t < 58 ? t -= 48 : t = (223 & t) - 65 + 10,
		e[i] = t;
	return e.reduce(function (r, t) {
		return r = 16 * r + t;
	}, 0);
}
module.exports = {
	formatTime: formatTime,
	ab2hex,
	str2buffer,
	inArray,
	endsWith,
	slice,
	formatDate,
	phoneFun,
	isDateYYYYDDMM,
	checkLicense,
	checkIdCard,
	checkHKMacao,
	IdentityCodeValid,
	isChineseName,
	luhnCheck,
	addresFun,
	stringHex2int
}
